package com.zyg.async;

import java.util.Random;
import java.util.concurrent.*;

/**
 * 内部整合了Executor和BlockingQueue,获取结果时按照任务完成的先后顺序获取
 * 消费者生产者模式
 * take：未获取到结果会阻塞
 * poll：未获取到结果会返回null
 */
public class CompletionServiceDemo {

    static ExecutorService executorService = Executors.newFixedThreadPool(100);

    public static void main(String[] args) {

        ExecutorCompletionService<Integer> executorCompletionService = new ExecutorCompletionService<>(executorService);
        executorCompletionService.submit(new CalculateScore(3));
        executorCompletionService.submit(new CalculateScore(2));
        executorCompletionService.submit(new CalculateScore(4));
        doSomeThing();
        int result = 0;
        for (int i = 0; i < 3; i++) {
            try {
                result += executorCompletionService.take().get();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (ExecutionException e) {
                e.printStackTrace();
            }
        }
        System.out.println(result);
        executorService.shutdown();

    }

    private static void doSomeThing() {

        System.out.println("main thread execute");
    }

    private static class CalculateScore implements java.util.concurrent.Callable<Integer> {
        private int num;

        public CalculateScore(int num) {
            this.num = num;
        }

        public CalculateScore() {
        }

        @Override
        public Integer call() throws Exception {
            Random random = new Random();
            TimeUnit.SECONDS.sleep(num);
            System.out.println(Thread.currentThread().getName());
            return random.nextInt(100);
        }
    }
}
